<template>
  <el-row class="row" type="flex" justify="center" align="middle">
    <el-col :span="8" class="loginForm">
      <el-form :model="loginForm" :rules="rules" ref="loginForm" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="loginForm.password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="startLogin">登錄</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<script>
/* eslint-disable-next-line */
import axios from "axios";
export default {
  data () {
    return {
      loginForm: {
        username: 'admin',
        password: '123456'
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 5, max: 10, message: '长度在 5 到 10 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    startLogin () {
      this.$refs.loginForm.validate(valid => {
        if (!valid) {
          return console.log('登陸失敗')
        }
        // 開始登錄
        axios
          .post('http://localhost:8888/api/private/v1/login', this.loginForm)
          .then(res => {
            if (res.data.meta.status === 200) {
              // 將後台返回的token保存到本地
              localStorage.setItem('token', res.data.data.token)
              this.$message({
                message: res.data.meta.msg,
                type: 'success',
                duration: 800
              })
              this.$router.push('home')
            } else {
              this.$message({
                message: res.data.meta.msg,
                type: 'warning',
                duration: 800
              })
            }
          })
      })
    },
    resetForm () {
      this.$refs.loginForm.resetFields()
    }
  }
}
</script>

<style>
* {
  margin: 0;
  padding: 0;
}

html,
body,
#app {
  height: 100%;
}
.row {
  height: 100%;
  background-color: #2a454d;
}
.loginForm {
  padding: 25px;
  background-color: #fff;
  border-radius: 15px;
}
</style>
